/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.forum.post;

import com.blandware.atleap.common.ForumModuleConstants;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.model.forum.Post;
import com.blandware.atleap.model.forum.Topic;
import com.blandware.atleap.service.forum.ForumManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.forum.PostForm;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebConstants;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>Shows a form for post creation.</p>
 * <p><a href="CallCreatePostAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.3 $ $Date: 2008/04/29 17:51:51 $
 * @struts.action path="/forum/post/callCreate"
 * name="postForm"
 * validate="false"
 * @struts.action-forward name="createPost"
 * path=".forum.post.create"
 * @struts.action-forward name="showForum"
 * path="/forum/forum/show.do"
 * redirect="true"
 */
public final class CallCreatePostAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) {

        PostForm postForm = (PostForm) form;

        HttpSession session = request.getSession();
        request.setAttribute("previewing", Boolean.FALSE);
        request.setAttribute("fullName", null);

        Long topicId = null;
        topicId = (Long) session.getAttribute(ForumModuleWebConstants.TOPIC_ID_KEY);

        if (topicId == null) {
            // no topic ID
            if (log.isDebugEnabled()) {
                log.debug("No topic ID was found while tried to create a post; going back to forums");
            }
            return mapping.findForward("showForum");
        }

        Long repliedPostId = null;
        if (!GenericValidator.isBlankOrNull(request.getParameter("postId"))) {
            try {
                repliedPostId = Long.valueOf(request.getParameter("postId"));
            } catch (NumberFormatException e) {
                repliedPostId = null;
            }
        }

        ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
        Topic topic = forumManager.retrieveTopic(topicId);
        if (topic == null) {
            // no topic found
            ActionMessages errors = new ActionMessages();
            errors.add("ownerNotFound", new ActionMessage("forum.post.errors.ownerNotFound"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        }

        Post repliedPost = null;
        boolean replying = false;
        if (repliedPostId != null) {
            replying = true;
            repliedPost = forumManager.retrievePost(repliedPostId);
            if (repliedPost == null) {
                // no post found
                ActionMessages errors = new ActionMessages();
                errors.add("repliedPostNotFound", new ActionMessage("forum.post.errors.repliedPostNotFound"));
                saveErrors(request, errors);
                return mapping.findForward("showForum");
            }
        }

        String rePrefix = "Re: ";
        String preparedBody;
        if (replying) {
            postForm.setSubject(rePrefix + repliedPost.getSubject());
            String repliedPostBody = ForumModuleWebUtil.wrapRepliedPostBody(repliedPost.getBody());
            postForm.setBody(repliedPostBody);
            preparedBody = StringUtil.asSingleLine(StringUtil.escapeDoubleQuotesForJs(repliedPostBody));
        } else {
            postForm.setSubject(rePrefix + topic.getFirstPost().getSubject());
            preparedBody = "";
        }
        request.setAttribute("preparedBody", preparedBody);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("createPost");
	}
}
